package com.study_online.interceptor;

import com.study_online.domain.User;
import com.study_online.utils.JjwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    // 定义一个线程域，存放用户id
    private static final ThreadLocal<User> tl = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String postToken = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIiwicGFzc3dvcmQiOiIwMDAwMDAiLCJuYW1lIjoienMiLCJleHAiOjE2NTExMzU3NDAsImlhdCI6MTY1MTEyODU0MCwianRpIjoiYmYxMzIxYjQtMjhjYy00ZDZmLWJmMGQtOWU5NDMxNTBmNjNiIn0.vILq7JZM1keX1J0XtRjAZf3VOVx8E1rKY0B3b2-88Fw";

        String postToken = request.getHeader("Authorization");
        Claims claims = JjwtUtil.parseJWT(postToken);
        String id = claims.getSubject();
        if (id!=null && postToken.equals(redisTemplate.opsForValue().get(id).toString())){
            String name = claims.get("username").toString();
            String password = claims.get("password").toString();
            User user = new User(Integer.parseInt(id),name,password);
            tl.set(user);
            return true;
        }
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        return false;
//        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        tl.remove();
    }

    public static User getUser() {
        return tl.get();
    }

}
